using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Eqwww.App.SystemManage;
using Eqwww.Domain.Models.SystemManage;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Eqwww.Code;
using AspNetCore.MultipartRequest;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Identity;
using Eqwww.Web.Areas.SystemManage.Models.MyAccount;
using Eqwww.App.Identity;
using Eqwww.Domain.Models.Identity;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    ///个人信息管理控制器
    [Area("SystemManage")]
    public class MyAccountController : ControllerBase
    {
        private UserApp _userApp;
        private PostApp _postApp;
        private OrganizeApp _organizeApp;
        private IWebHostEnvironment _hostingEnvironment;
        private SignInManager<UserModel> _signInManager;
        public MyAccountController(UserApp userApp, PostApp postApp, OrganizeApp organizeApp, IWebHostEnvironment env, SignInManager<UserModel> signInManager)
        {
            _userApp = userApp;
            _postApp = postApp;
            _organizeApp = organizeApp;
            _hostingEnvironment = env;
            _signInManager = signInManager;
        }

        public IActionResult Index()
        {
            var model = _userApp.GetUserAsync(User).Result;
            return View(model);
        }

        public IActionResult MyPermissions()
        {
            var user = _userApp.GetUserAsync(User).Result;
            if (user == null)
                return NotFound();

            ViewData["Strategorys"] = _userApp.GetStrategorysByUser(user.Id);
            ViewData["Permissions"] = _userApp.GetPermissionsByUser(user.Id);
            return View();
        }

        public IActionResult ChangeEmail()
        {
            var user = _userApp.GetUserAsync(User).Result;
            var model = new ChangeEmailModel
            {
                EmailAddress = user.Email
            };
            return View(model);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ChangeEmailSubmit(ChangeEmailModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(Common.ModelStateErrorResult(ModelState));
            }

            var user = _userApp.GetUserAsync(User).Result;
            if (user == null)
                return Error("未找到指定用户");

            user.Email = model.EmailAddress;
            var result = _userApp.UpdateAsync(user).Result;
            if (result.Succeeded)
                return Success("操作成功!");
            else
            {
                var message = string.Empty;
                foreach (var err in result.Errors)
                {
                    message += err.Description + "<br />";
                }
                return Error(message);
            }
        }

        public IActionResult ChangeContact()
        {
            var user = _userApp.GetUserAsync(User).Result;
            var model = new ChangeContactViewModel
            {
                Contact = user.Contact
            };
            return View(model);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ChangeContactSubmit(ChangeContactViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(Common.ModelStateErrorResult(ModelState));
            }

            var user = _userApp.GetUserAsync(User).Result;
            if (user == null)
                return Error("未找到指定用户");

            user.Contact = model.Contact;
            var result = _userApp.UpdateAsync(user).Result;
            if (result.Succeeded)
                return Success("操作成功!");
            else
            {
                var message = string.Empty;
                foreach (var err in result.Errors)
                {
                    message += err.Description + "<br />";
                }
                return Error(message);
            }
        }

        public IActionResult ChangeRealName()
        {
            var user = _userApp.GetUserAsync(User).Result;
            var model = new ChangeRealNameModel
            {
                RealName = user.RealName
            };
            return View(model);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ChangeRealNameSubmit(ChangeRealNameModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(Common.ModelStateErrorResult(ModelState));
            }

            var user = _userApp.GetUserAsync(User).Result;
            if (user == null)
                return Error("未找到指定用户");

            user.RealName = model.RealName;
            var result = _userApp.UpdateAsync(user).Result;
            if (result.Succeeded)
                return Success("操作成功!");
            else
            {
                var message = string.Empty;
                foreach (var err in result.Errors)
                {
                    message += err.Description + "<br />";
                }
                return Error(message);
            }
        }

        public IActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        public async Task<IActionResult> ChangePasswordSubmitAsync(ChangePasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(Common.ModelStateErrorResult(ModelState));
            }

            var user = await _userApp.GetUserAsync(User);
            if (user == null)
            {
                return Error("未找到当前用户信息");
            }

            var changePasswordResult = await _userApp.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
            if (!changePasswordResult.Succeeded)
            {
                var err = string.Empty;
                foreach (var error in changePasswordResult.Errors)
                {
                    err += error.Description + "<br />";
                }
                return Error(err);
            }

            await _signInManager.RefreshSignInAsync(user);


            return Success("操作成功!");
        }

        public IActionResult Avatar()
        {
            return View();
        }

        public IActionResult CustomAvatar()
        {
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        public IActionResult AvatarSubmit(string Avatar)
        {
            if (string.IsNullOrEmpty(Avatar))
            {
                return Error("未获取到有效的头像路径");
            }

            var user = _userApp.GetUserAsync(User).Result;
            user.Avatar = Avatar;
            var result = _userApp.UpdateAsync(user).Result;
            if (result.Succeeded)
                return Success("操作成功!");
            else
            {
                return Error("未知错误");
            }
        }

        [HttpPost]
        [ExceptionFilter]
        [AspNetCore.MultipartRequest.DisableFormValueModelBinding]
        public async Task<IActionResult> CustomAvatarSubmitAsync()
        {

            var user = _userApp.GetUserAsync(User).Result;
            if (user == null)
                return Error("未找到指定用户");

            var files = Request.Form.Files;
            var formFile = files[0];
            var path = Path.Combine(_hostingEnvironment.WebRootPath + "/upload/avatars/temps/" + System.Guid.NewGuid().ToString() + ".jpg");

            using (var stream = new FileStream(path, FileMode.CreateNew))
            {
                await formFile.CopyToAsync(stream);
            }

            var x = Request.Query["x"].ToString();
            var y = Request.Query["y"].ToString();
            var width = Request.Query["width"].ToString();
            var height = Request.Query["height"].ToString();

            var angle = new Rectangle(new Point(int.Parse(x), int.Parse(y)), new Size(int.Parse(width), int.Parse(height)));
            var avatarPath = "/upload/avatars/" + System.Guid.NewGuid().ToString() + ".jpg";

            using (var img = Image.Load(path))
            {
                using (Image<Rgba32> destRound = img.Clone(_ => _.Crop(angle)))
                {
                    destRound.Mutate(_ => _.Resize(256, 256));
                    destRound.Save(Path.Combine(_hostingEnvironment.WebRootPath + avatarPath));
                }
            }

            user.Avatar = avatarPath;
            var result = await _userApp.UpdateAsync(user);

            return Success(files.Count().ToString());

        }
    }


}